package com.ryl.yomall.product.service.impl;

import com.ryl.yomall.product.service.TestService;
import com.sun.org.omg.CORBA.RepositoryIdSeqHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Collections;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Date 20:22
 * @Author ryl
 */
@Service
public class TestServiceImpl implements TestService {
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void testLock() {
        String uuid = UUID.randomUUID ( ).toString ( );
        Boolean lock = redisTemplate.opsForValue ( ).setIfAbsent ( "lock" ,uuid ,3,TimeUnit.SECONDS);
        if(lock){
            //上锁
            Integer num = (Integer) redisTemplate.opsForValue ( ).get ( "num" );
            num++;
            redisTemplate.opsForValue ().set ( "num",num );
            String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return tostring(redis.call('del',KEYS[1])) else return 0 end";
            this.redisTemplate.execute(new DefaultRedisScript<> (script), Collections.singletonList("lock"), uuid);

        }else {
            //未上锁

                testLock ();


        }

    }
//    public static final Lock lock=new ReentrantLock ();
//    @Override
//    public void testLock() {
//        lock.lock ();
//        try {
//
//            Integer num = (Integer) redisTemplate.opsForValue ( ).get ( "num" );
//            if(!StringUtils.isEmpty ( num )){
//                num++;
//                redisTemplate.opsForValue ().set ( "num" ,num);
//            }
//
//        } finally {
//            lock.unlock ();
//        }
//    }
}
